package com.gitee.zycra.future.job.web.handler;

import com.gitee.zycra.future.job.service.JobNodeService;
import com.gitee.zycra.future.job.service.JobRunningService;
import com.gitee.zycra.future.job.service.JobScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zycra
 */
@Slf4j
@Component
public class JobSyncHandler {

    @Autowired
    private JobRunningService jobRunningService;

    @Autowired
    private JobScheduleService jobScheduleService;

    @Autowired
    private JobNodeService jobNodeService;

    private final ScheduledThreadPoolExecutor syncExecutor = new ScheduledThreadPoolExecutor(6);

    private static final long HEART_BEATS_INTERVAL = 10L;

    @PostConstruct
    public void init() {

        // 计算下次执行时间
        syncExecutor.scheduleAtFixedRate(() -> jobScheduleService.calculateScheduleTime(), 0L, HEART_BEATS_INTERVAL, TimeUnit.SECONDS);

        // 选择节点执行
        syncExecutor.scheduleAtFixedRate(() -> jobRunningService.dispatch(), 0L, HEART_BEATS_INTERVAL, TimeUnit.SECONDS);

        // 调度通知
        syncExecutor.scheduleAtFixedRate(() -> jobNodeService.notifyNode(), 0L, HEART_BEATS_INTERVAL, TimeUnit.SECONDS);

        // 转移已完成任务到执行日志
        syncExecutor.scheduleAtFixedRate(() -> jobRunningService.transferToLog(), 0L, HEART_BEATS_INTERVAL, TimeUnit.SECONDS);

        // 同步节点状态
        syncExecutor.scheduleAtFixedRate(() -> jobNodeService.syncNodeRunningStatus(), 0L, HEART_BEATS_INTERVAL, TimeUnit.SECONDS);

        // 超时任务处理
        syncExecutor.scheduleAtFixedRate(() -> jobRunningService.syncTimeoutStatus(), 0L, HEART_BEATS_INTERVAL, TimeUnit.SECONDS);
    }
}
